package gameoflive;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Random;


public class GameOfLive
{
    private static GameOfLive instance;
    
    public static synchronized GameOfLive getInstance()
    {
        if (instance == null)
        {
            instance = new GameOfLive();
        }
        return instance;
    }
    
    private Point maxXY;
    
    private List<Cell> cells;
    
    private int generation;
    private int livingCells = 0;
    private int livingCellsIdentical = 0;
    
    // Lebende Zellen generieren
    private static Random RANDOM = new Random(System.currentTimeMillis());

    protected GameOfLive()
    {
        initCells();
    }
    
    public Point getMaxXY()
    {
        return maxXY;
    }
    
    public int getGeneration()
    {
        return generation;
    }
    
    public Cell getCell(Point position)
    {
        return getCell((int) position.getWidth(), (int) position.getHeight());
    }
    
    public Cell getCell(int x, int y)
    {
        if (x < 0 || x > maxXY.getWidth())
        {
            throw new IndexOutOfBoundsException(x + " not in 0-" + maxXY.getWidth());
        }
        if (y < 0 || y > maxXY.getHeight())
        {
            throw new IndexOutOfBoundsException(y + " not in 0-" + maxXY.getHeight());
        }
        Cell cell = null;
        int index = calculateIndex(x, y, (int) maxXY.getWidth());
        if (index == cells.size())
        {
            cells.add(new Cell(x, y, false, false));
        }
        cell = cells.get(index);
//        Game.log("getCell: " + index + " = " + cell);
        return cell;
    }
    
    private int calculateIndex(int x, int y, int maxWidth)
    {
        int index = 0;
        index = x + y * maxWidth;
//        Game.log("calculateIndex: x=" + x + ", y=" + y + " = " + index);
        return index;
    }
    
    public List<Cell> getCells()
    {
        return cells;
    }
    
    private void initCells()
    {
        this.cells = new ArrayList<Cell>();
    }
    
    private static boolean INIT_GENERATION;
    
    public boolean initGeneration()
    {
        return INIT_GENERATION;
    }
    
    public boolean prepareNextGeneration()
    {
        if (initGeneration())
        {
            return false;
        }
        try
        {
            generation++;
    //        Game.log("prepareNextGeneration: " + generation);
            for (Cell cell : cells)
            {
                int livingNeighbors = cell.countLivingNeighbors();
                boolean surviving = cell.isAlive();
                if (cell.isAlive())
                {
                    if (livingNeighbors == 2 || livingNeighbors == 3)
                    {
                        surviving = true;
                    }
                    else
                    {
                        surviving = false;
                    }
                }
                else
                {
                    if (livingNeighbors == 3)
                    {
                        surviving = true;
                    }
                }
    //            Game.log("Cell surving: " + surviving);
                cell.setSurviving(surviving);
            }
            int alive = 0;
            for (Cell cell : cells)
            {
                cell.setAlive(cell.isSurviving());
                if (cell.isAlive())
                {
                    alive++;
                }
            }
            if (alive == livingCells)
            {
                livingCellsIdentical++;
            }
            else
            {
                livingCellsIdentical = 0;
            }
            livingCells = alive;
            Game.log("Generation " + getGeneration() + "; " + livingCells + " Living Cells");
            boolean prepareNextGeneration = true;
            if (livingCells <= 0)
            {
                Game.log("No more living cells");
                prepareNextGeneration = false;
            }
            else if (livingCellsIdentical > 50)
            {
                prepareNextGeneration = false;
            }
            return prepareNextGeneration;
        }
        catch (IndexOutOfBoundsException ex)
        {
            return false;
        }
        catch (ConcurrentModificationException ex)
        {
            return false;
        }
    }
    
    public void addLivingCells(int count)
    {
//        Game.log("addLivingCells()");
        List<Point> livingCells = new ArrayList<Point>();
        do
        {
            Point position = new Point(RANDOM.nextInt((int) (maxXY.getWidth() + 1)), 
                                       RANDOM.nextInt((int) (maxXY.getHeight() + 1)));
            if (livingCells.contains(position) == false)
            {
                livingCells.add(position);
            }
        }
        while (livingCells.size() < count);
        // reset count
        count = 0;
        for (Cell cell : cells)
        {
            if (livingCells.contains(cell.getPosition()))
            {
                cell.setAlive(true);
                cell.setSurviving(true);
            }
        }
//        Game.log(count + " living cells added");
    }
    
    public void resetGeneration()
    {
        INIT_GENERATION = true;
        Game.getInstance().doPauseRendering(true);
//        Game.log("resetGeneration()");
        for (Cell cell : cells)
        {
//            Game.log(".", false);
            cell.setAlive(false);
        }
//        Game.log("");
        addLivingCells(RANDOM.nextInt(maxXY.getX() * maxXY.getY()));
        generation = 0;
        INIT_GENERATION = false;
        Game.getInstance().doPauseRendering(false);
    }
    
    public void initGeneration(int x, int y)
    {
        INIT_GENERATION = true;
        Game.getInstance().doPauseRendering(true);
        int count = x * y;
//        Game.log("initGeneration: " + count + " cells");
        // Anzahl Zellen
        maxXY = new Point(x, y);
        // Liste generieren
        initCells();
        for (y = 0; y < maxXY.getHeight(); y++)
        {
            for (x = 0; x < maxXY.getWidth(); x++)
            {
                getCell(x, y);
            }
        }
        Game.log("buildMap() complete, " + cells.size() + " cells created");
        addLivingCells(RANDOM.nextInt(count));
        generation = 0;
        INIT_GENERATION = false;
        Game.getInstance().doPauseRendering(false);
    }
}
